const express = require('express')
const { query, param, validationResult } = require('express-validator')
const { query: dbQuery } = require('../config/database')
const { optionalAuth, authenticateToken } = require('../middleware/auth')

const router = express.Router()

/**
 * @swagger
 * components:
 *   schemas:
 *     Novel:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *         title:
 *           type: string
 *         author:
 *           type: string
 *         description:
 *           type: string
 *         cover_url:
 *           type: string
 *         category:
 *           type: string
 *         tags:
 *           type: array
 *           items:
 *             type: string
 *         status:
 *           type: string
 *           enum: [serializing, completed, paused]
 *         word_count:
 *           type: integer
 *         chapter_count:
 *           type: integer
 *         rating:
 *           type: number
 *           format: float
 *         view_count:
 *           type: integer
 *         like_count:
 *           type: integer
 *         is_vip:
 *           type: boolean
 *         created_at:
 *           type: string
 *           format: date-time
 */

/**
 * @swagger
 * /api/novels:
 *   get:
 *     summary: 获取小说列表
 *     tags: [小说]
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 20
 *         description: 每页数量
 *       - in: query
 *         name: category
 *         schema:
 *           type: string
 *         description: 分类
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [serializing, completed, paused]
 *         description: 状态
 *       - in: query
 *         name: sort
 *         schema:
 *           type: string
 *           enum: [latest, popular, rating, view_count]
 *           default: latest
 *         description: 排序方式
 *       - in: query
 *         name: search
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *     responses:
 *       200:
 *         description: 获取成功
 */
router.get(
  '/',
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('每页数量必须在1-100之间'),
    query('category').optional().isString().withMessage('分类必须是字符串'),
    query('status')
      .optional()
      .isIn(['serializing', 'completed', 'paused'])
      .withMessage('状态值无效'),
    query('sort')
      .optional()
      .isIn(['latest', 'popular', 'rating', 'view_count'])
      .withMessage('排序方式无效'),
    query('search').optional().isString().withMessage('搜索关键词必须是字符串')
  ],
  optionalAuth,
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const {
        page = 1,
        limit = 20,
        category,
        status,
        sort = 'latest',
        search
      } = req.query

      const offset = (page - 1) * limit
      let whereConditions = []
      let queryParams = []

      // 构建查询条件
      if (category) {
        whereConditions.push('category = ?')
        queryParams.push(category)
      }

      if (status) {
        whereConditions.push('status = ?')
        queryParams.push(status)
      }

      if (search) {
        whereConditions.push(
          '(title LIKE ? OR author LIKE ? OR description LIKE ?)'
        )
        const searchTerm = `%${search}%`
        queryParams.push(searchTerm, searchTerm, searchTerm)
      }

      const whereClause =
        whereConditions.length > 0
          ? `WHERE ${whereConditions.join(' AND ')}`
          : ''

      // 排序条件
      let orderBy
      switch (sort) {
        case 'popular':
          orderBy = 'ORDER BY favorite_count DESC, view_count DESC'
          break
        case 'rating':
          orderBy = 'ORDER BY rating DESC, view_count DESC'
          break
        case 'view_count':
          orderBy = 'ORDER BY view_count DESC'
          break
        default:
          orderBy = 'ORDER BY created_at DESC'
      }

      // 查询小说列表
      const novels = await dbQuery(
        `
      SELECT 
        id, title, author, description, cover_url, category, tags, 
        status, word_count, chapter_count, rating, view_count, favorite_count, 
        is_vip, created_at
      FROM novels 
      ${whereClause}
      ${orderBy}
      LIMIT ? OFFSET ?
    `,
        [...queryParams, parseInt(limit), offset]
      )

      // 获取总数
      const totalResult = await dbQuery(
        `
      SELECT COUNT(*) as total FROM novels ${whereClause}
    `,
        queryParams
      )

      const total = totalResult[0].total

      // 处理标签字段
      const processedNovels = novels.map(novel => ({
        ...novel,
        tags: novel.tags ? JSON.parse(novel.tags) : []
      }))

      res.paginate(processedNovels, parseInt(page), parseInt(limit), total)
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/novels/{id}:
 *   get:
 *     summary: 获取小说详情
 *     tags: [小说]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 小说ID
 *     responses:
 *       200:
 *         description: 获取成功
 *       404:
 *         description: 小说不存在
 */
router.get(
  '/:id',
  [param('id').isInt({ min: 1 }).withMessage('小说ID必须是正整数')],
  optionalAuth,
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const novelId = req.params.id

      // 获取小说详情
      const novels = await dbQuery(
        `
      SELECT 
        id, title, author, description, cover_url, category, tags,
        status, word_count, chapter_count, rating, view_count, like_count,
        is_vip, created_at, updated_at
      FROM novels 
      WHERE id = ?
    `,
        [novelId]
      )

      if (novels.length === 0) {
        return res.error('小说不存在', 'NOVEL_NOT_FOUND', 404)
      }

      const novel = novels[0]
      novel.tags = novel.tags ? JSON.parse(novel.tags) : []

      // 增加浏览量
      await dbQuery(
        'UPDATE novels SET view_count = view_count + 1 WHERE id = ?',
        [novelId]
      )
      novel.view_count += 1

      // 获取章节列表（前10章）
      const chapters = await dbQuery(
        `
      SELECT id, title, chapter_number, word_count, is_vip, price, created_at
      FROM chapters 
      WHERE novel_id = ? 
      ORDER BY chapter_number ASC 
      LIMIT 10
    `,
        [novelId]
      )

      // 如果用户已登录，检查是否已收藏
      let isInBookshelf = false
      let readingProgress = null
      if (req.user) {
        const bookshelfResult = await dbQuery(
          'SELECT is_favorite, reading_progress FROM user_bookshelf WHERE user_id = ? AND novel_id = ?',
          [req.user.id, novelId]
        )

        if (bookshelfResult.length > 0) {
          isInBookshelf = true
          readingProgress = bookshelfResult[0].reading_progress
        }
      }

      res.success(
        {
          novel,
          chapters,
          isInBookshelf,
          readingProgress
        },
        '获取小说详情成功'
      )
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/novels/{id}/chapters:
 *   get:
 *     summary: 获取小说章节列表
 *     tags: [小说]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 小说ID
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 50
 *         description: 每页数量
 *     responses:
 *       200:
 *         description: 获取成功
 */
router.get(
  '/:id/chapters',
  [
    param('id').isInt({ min: 1 }).withMessage('小说ID必须是正整数'),
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('每页数量必须在1-100之间')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const novelId = req.params.id
      const { page = 1, limit = 50 } = req.query
      const offset = (page - 1) * limit

      // 检查小说是否存在
      const novels = await dbQuery(
        'SELECT id, title FROM novels WHERE id = ?',
        [novelId]
      )
      if (novels.length === 0) {
        return res.error('小说不存在', 'NOVEL_NOT_FOUND', 404)
      }

      // 获取章节列表
      const chapters = await dbQuery(
        `
      SELECT 
        id, title, chapter_number, word_count, is_vip, price, 
        view_count, created_at
      FROM chapters 
      WHERE novel_id = ? 
      ORDER BY chapter_number ASC
      LIMIT ? OFFSET ?
    `,
        [novelId, parseInt(limit), offset]
      )

      // 获取总章节数
      const totalResult = await dbQuery(
        'SELECT COUNT(*) as total FROM chapters WHERE novel_id = ?',
        [novelId]
      )

      const total = totalResult[0].total

      res.paginate(chapters, parseInt(page), parseInt(limit), total)
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/novels/categories:
 *   get:
 *     summary: 获取小说分类列表
 *     tags: [小说]
 *     responses:
 *       200:
 *         description: 获取成功
 */
router.get('/categories', async (req, res, next) => {
  try {
    // 获取所有分类及其小说数量
    const categories = await dbQuery(`
      SELECT 
        category, 
        COUNT(*) as novel_count
      FROM novels 
      GROUP BY category 
      ORDER BY novel_count DESC
    `)

    res.success(categories, '获取分类列表成功')
  } catch (error) {
    next(error)
  }
})

/**
 * @swagger
 * /api/novels/{id}/like:
 *   post:
 *     summary: 点赞/取消点赞小说
 *     tags: [小说]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 小说ID
 *     responses:
 *       200:
 *         description: 操作成功
 */
router.post(
  '/:id/like',
  [
    authenticateToken,
    param('id').isInt({ min: 1 }).withMessage('小说ID必须是正整数')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const novelId = req.params.id
      const userId = req.user.id

      // 检查小说是否存在
      const novels = await dbQuery(
        'SELECT id, like_count FROM novels WHERE id = ?',
        [novelId]
      )
      if (novels.length === 0) {
        return res.error('小说不存在', 'NOVEL_NOT_FOUND', 404)
      }

      // 这里简化处理，实际项目中应该有专门的点赞表来记录用户点赞行为
      // 目前只是增加点赞数，不记录具体是哪个用户点赞
      await dbQuery(
        'UPDATE novels SET like_count = like_count + 1 WHERE id = ?',
        [novelId]
      )

      res.success(null, '点赞成功')
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/novels/trending:
 *   get:
 *     summary: 获取热门小说
 *     tags: [小说]
 *     parameters:
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 返回数量
 *     responses:
 *       200:
 *         description: 获取成功
 */
router.get(
  '/trending',
  [
    query('limit')
      .optional()
      .isInt({ min: 1, max: 50 })
      .withMessage('返回数量必须在1-50之间')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const { limit = 10 } = req.query

      // 获取热门小说（基于最近7天的浏览量和点赞数）
      const novels = await dbQuery(
        `
      SELECT 
        id, title, author, cover_url, category, rating, 
        view_count, like_count, chapter_count
      FROM novels 
      ORDER BY (view_count * 0.3 + like_count * 0.7) DESC
      LIMIT ?
    `,
        [parseInt(limit)]
      )

      res.success(novels, '获取热门小说成功')
    } catch (error) {
      next(error)
    }
  }
)

module.exports = router
